package cn.xshi.gateway.route.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import cn.xshi.gateway.BaseResult;
import cn.xshi.gateway.route.model.DynamicRoute;
import cn.xshi.gateway.util.GatewayRedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.route.RouteDefinition;
import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Set;
/**
 * @Desc 动态路由设置
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class DynamicRouteEvent {

    public static final String JEHC_ROUTE = "JEHC:CLOUD:JEHC-ROUTE";// 网关动态路由Key

    @Resource
    DynamicRouteService dynamicRouteService;

    @Resource
    GatewayRedisUtil gatewayRedisUtil;


    private static boolean isRun = true;
    private static Long updateTime = 0L;
    private final Object lock = new Object();
    private static final int times = 60*10*1000;//600秒同步一次

    /**
     * 查询记录并同步
     */
    public void execute() {
        new Thread(new DynamicRouteRunnable()).start();
    }

    /**
     *
     */
    class DynamicRouteRunnable implements Runnable {
        public void run() {
            while (isRun){
                try {
                    long endTime = System.currentTimeMillis();
                    if(null == updateTime || updateTime == 0L){
                        updateTime =  System.currentTimeMillis()-times;//推迟1分钟，作为开始时间
                    }
                    initDynamicRouteInfo();
                    updateTime = endTime;//修改最后更新时间
                    Thread.sleep(times);
                }catch (Exception e){
                    log.error("处理路由异常：{}",e);
                }
            }
        }
    }

    /**
     * 初始化数据
     */
    public void initDynamicRouteInfo(){
        try{
            Set<String> keys = gatewayRedisUtil.hKeys(JEHC_ROUTE);
            if(!CollectionUtil.isEmpty(keys)){
                for(Iterator it = keys.iterator(); it.hasNext(); ) {
                    String routeJson = ""+gatewayRedisUtil.hget(JEHC_ROUTE,it.next().toString());
                    if(StringUtils.isEmpty(routeJson)){
                        continue;
                    }
                    DynamicRoute dynamicRoute = JSON.parseObject(routeJson, DynamicRoute.class);
                    if(null != dynamicRoute && (1 == dynamicRoute.getStatus()|| "1".equals(dynamicRoute.getDelFlag()))){//如果关闭或删除调用删除逻辑
                        BaseResult result = dynamicRouteService.deleteRouteDefinition(dynamicRoute.getRouteId());
                        log.info("删除网关路由，结果：{}",result);
                        continue;
                    }
                    RouteDefinition routeDefinition = dynamicRouteService.doRouteDefinition(dynamicRoute);//设置路由
                    if(null != routeDefinition){
                        BaseResult baseResult = dynamicRouteService.updateRouteDefinition(routeDefinition);//更新逻辑
                        if(baseResult.getSuccess()){
                            log.info("更新路由成功，路由信息：{}",dynamicRoute);
                        }else{
                            log.info("更新路由失败，路由信息：{}，{}",dynamicRoute,baseResult.getMessage());
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("初始化路由信息失败：{}",e);
        }
    }

    /**
     *  销毁
     */
    public void destroy(){
        isRun = false;
    }
}
